package com.weixin.paleituo.help;

import android.content.Context;

import com.weixin.paleituo.activity.LoginActivity;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.eventbus.ExitLoginSuccess;
import com.weixin.paleituo.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import io.reactivex.functions.Function;

/**
 * Author yichao
 * Time  2018/1/25 16:29
 * Dest  统一处理
 */

public class FunctionHelp<T> implements Function<StatusCode<T>, T> {

    private Context mContext;

    public FunctionHelp(Context context) {
        mContext = context;
    }

    @Override
    public T apply(StatusCode<T> statusCode) throws Exception {
        if (statusCode.isFlag()) {
            return statusCode.getData();
        } else {
            switch (statusCode.getNumber()) {
                case 2001:
                    //请求失败
                    ToastUtils.makeText(statusCode.getDetailMsg());
                    break;
                case 2002:
                    //未知错误
                    ToastUtils.makeText(statusCode.getDetailMsg());
                    break;
                case 2003:
                    //参数错误
                    ToastUtils.makeText(statusCode.getDetailMsg());
                    break;
                case 3001:
                    //无效token
                    ToastUtils.makeText("登录过期，请重新登录");
                    BaseApplication.isLoginSuccess=false;
                    BaseApplication.sUserInfoBean=null;
                    LoginActivity.startActivity(mContext,true);
                    EventBus.getDefault().post(new ExitLoginSuccess());
                    break;
                case 3002:
                    //token已过期
                    ToastUtils.makeText("登录过期，请重新登录");
                    BaseApplication.isLoginSuccess=false;
                    BaseApplication.sUserInfoBean=null;
                    LoginActivity.startActivity(mContext,true);
                    EventBus.getDefault().post(new ExitLoginSuccess());
                    break;
                case 5000:
                    //服务端错误
                    ToastUtils.makeText(statusCode.getDetailMsg());
                    break;
            }

        }
        return null;
    }
}
